import { ref, computed } from 'vue';
import { defineStore } from 'pinia';

export const useWeatherStore = defineStore('weather', () => {
  //顶部栏和城市搜索组件数据同步
  const weatherData = ref('');
  const setData = (data) => {
    weatherData.value = data;
    console.log('weather获取数据成功');
  };

  //城市搜索点击事件触发添加城市状态
  const addCity = ref(false);
  const setAddCity = (data) => {
    addCity.value = data;
    console.log('进入添加城市状态');
  };

  //记录查询后的城市和adcode信息
  const cityInfo = ref({
    city: '',
    adcode: '',
  });
  const setCityInfo = (data) => {
    cityInfo.value.city = data.city;
    cityInfo.value.adcode = data.adcode;
    console.log('weather记录的城市是', cityInfo.value);
  };

  //判断当前城市是否存在
  const isExist = (city) => {
    if (cityList.value.some((item) => item.city.includes(city))) {
      addCity.value = false;
    } else {
      addCity.value = true;
    }
  };

  //把城市和adcode信息存进数组
  const cityList = ref(JSON.parse(localStorage.getItem('cityList')) || []);
  const setCityList = () => {
    cityList.value.push({ ...cityInfo.value }); //深拷贝
    // 把数组转换为字符串并存储在本地存储中
    localStorage.setItem('cityList', JSON.stringify(cityList.value));
    console.log(`${cityInfo.value.city}已添加`);
    console.log(cityList.value);
  };

  //删除城市
  const deleteCity = (index) => {
    cityList.value.splice(index, 1);
    // 删除的同时也删除本地数据(删除数据后更新一次本地数据)
    localStorage.setItem('cityList', JSON.stringify(cityList.value));
    console.log('该城市已删除');
    console.log(cityList.value);
  };

  //收藏列表发送请求后更新本地城市列表
  const setCityTemp = (temp, adcode) => {
    const targetCity = cityList.value.find((item) => item.adcode === adcode);
    if (targetCity) {
      targetCity.temp = temp;
      console.log('更新成功');
    } else {
      console.log('更新失败');
      console.log(cityList.value);
      console.log(adcode);
    }
    localStorage.setItem('cityList', JSON.stringify(cityList.value));
  };
  return {
    weatherData,
    setData,
    addCity,
    setAddCity,
    cityInfo,
    setCityInfo,
    cityList,
    isExist,
    setCityList,
    deleteCity,
    setCityTemp,
  };
});
